<template>
  <div>
    <h2>用户管理</h2>

    <!-- 统一操作区 -->
    <el-row style="margin-bottom: 12px">
      <el-col :span="12">
        <el-button type="primary" @click="openAdd">新增用户</el-button>
      </el-col>
      <el-col :span="12" style="text-align: right">
        <el-input
            v-model="kw"
            placeholder="姓名/登录名"
            clearable
            style="width: 220px"
            @clear="load"
            @keyup.enter="load"
        >
          <template #append>
            <el-button @click="load">搜索</el-button>
          </template>
        </el-input>
      </el-col>
    </el-row>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-change="load">
      <el-tab-pane label="管理员" name="admin" />
      <el-tab-pane label="护工" name="caregiver" />
      <el-tab-pane label="前台" name="reception" />
    </el-tabs>

    <!-- 用户表格 + 分页 -->
    <UserTable
        :role="activeTab"
        :kw="kw"
        @on-add="openAdd"
        @on-edit="openEdit"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="show"
        :title="isAdd ? '新增用户' : '编辑用户'"
        width="420px"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="登录名">
          <el-input v-model="form.loginName" />
        </el-form-item>
        <el-form-item label="角色">
          <el-tag>{{ activeTab }}</el-tag>
        </el-form-item>
        <el-form-item label="初始密码" v-if="isAdd">
          <el-input
              v-model="form.password"
              type="password"
              show-password
              placeholder="留空则默认 123456"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { saveUser } from '@/api/user'
import UserTable from '@/components/UserTable.vue'

const activeTab = ref('admin')
const kw = ref('')
const show = ref(false)
const isAdd = ref(true)
const form = ref({})

/* 搜索 / 切换标签 */
const load = () => {
  // 由 UserTable 自己监听 kw + activeTab 变化，这里只需触发事件
}

/* 新增 */
const openAdd = () => {
  form.value = { name: '', loginName: '', password: '' }
  isAdd.value = true
  show.value = true
}

/* 编辑（子组件抛事件） */
const openEdit = (row) => {
  form.value = { id: row.id, name: row.name, loginName: row.loginName }
  isAdd.value = false
  show.value = true
}

/* 提交 */
const submit = async () => {
  try {
    await saveUser(activeTab.value, { ...form.value, status: 1 })
    ElMessage.success(isAdd.value ? '新增成功' : '修改成功')
    show.value = false
    // 通知子组件刷新
    load()
  } catch (e) {
    ElMessage.error(isAdd.value ? '新增失败' : '修改失败')
  }
}
</script>